from typing import List, Optional
from .models import BBox, Detection, FrameDetections
import cv2


def validate_video_file(video_path: str) -> bool:
    """Check if a video file is valid and can be opened."""
    try:
        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            return False
        cap.release()
        return True
    except:
        return False


def get_video_properties(video_path: str) -> Optional[dict]:
    """Get basic properties of a video file."""
    try:
        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            return None

        properties = {
            'width': int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
            'height': int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
            'fps': cap.get(cv2.CAP_PROP_FPS),
            'frame_count': int(cap.get(cv2.CAP_PROP_FRAME_COUNT)),
            'duration': int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) / cap.get(cv2.CAP_PROP_FPS)
        }
        cap.release()
        return properties
    except:
        return None


def list_available_cameras(max_test: int = 10) -> List[int]:
    """List available camera indices."""
    available = []
    for i in range(max_test):
        cap = cv2.VideoCapture(i)
        if cap.isOpened():
            available.append(i)
            cap.release()
    return available


import json

def save_detections_to_json(
    detections: List[FrameDetections],
    json_path: str
) -> bool:
    try:
        serializable_data = []

        for frame in detections:
            frame_dict = {
                "timestamp": frame.timestamp,
                "detections": [
                    {
                        "class_id": det.class_id,
                        "confidence": det.confidence,
                        "bbox": {
                            "x1": det.bbox.x1,
                            "y1": det.bbox.y1,
                            "x2": det.bbox.x2,
                            "y2": det.bbox.y2
                        }
                    }
                    for det in frame.detections
                ]
            }
            serializable_data.append(frame_dict)

        with open(json_path, 'w') as f:
            json.dump(serializable_data, f, indent=2)

        return True

    except Exception as e:
        print(f"Failed to save detections to JSON: {str(e)}")
        return False
